package edu.visualization.homework.draw;

import java.awt.Color;
import java.awt.Graphics;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;

import edu.visualization.homework.entity.Constructor;
import edu.visualization.homework.entity.TreeNode;
import edu.visualization.homework.entity.TreeUtils;

public class MTreePic extends JPanel {

	private static final long serialVersionUID = 1L;
	private TreeNode root;
	private int r;

	private int upbound = 20;
	private int leftbound = 20;

	private static int length = 50;

	public MTreePic(TreeNode root, int width, int height, int r) {
		super();
		this.setLayout(null);
		this.root = root;
		this.r = r;
		this.setBounds(0, 0, width, height);
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		paintRound(g, root);
		paintLine(g, root);
	}

	private void paintRound(Graphics g, TreeNode root) {
		if (root != null) {
			int x = (int) (root.getX() * length) + leftbound;
			int y = (int) (root.getY() * length) + upbound;
			String value = root.getValue();
			System.out.println("x:" + x + " y:" + y + " value:" + value);
			g.drawOval(x, y, r * 2, r * 2);
			g.setColor(Color.red);
			g.drawString(value, x + (int) (r * 0.85), y + (int) (r * 1.25));
			g.setColor(Color.black);
			if (root.getChildren() != null) {
				for (TreeNode node : root.getChildren()) {
					paintRound(g, node);
				}
			}
		}
	}

	private void paintLine(Graphics g, TreeNode root) {
		if (root != null) {
			if (root.getChildren() != null) {
				int xp = (int) (root.getX() * length) + leftbound + r;
				int yp = (int) (root.getY() * length) + upbound + r + r;

				for (TreeNode node : root.getChildren()) {
					int x = (int) (node.getX() * length) + leftbound + r;
					int y = (int) (node.getY() * length) + upbound;
					g.drawLine(xp, yp, x, y);
					paintLine(g, node);
				}
			}
		}
	}

	public static void main(String[] args) {

		File file = new File("../homework");
		TreeNode root = Constructor.getTheTree(file);
		TreeUtils.setTreeY(root, 0);
		// 获得树的高度和宽度
		double width = TreeUtils.postOrderTra(root, 0);
		double higth = TreeUtils.getDepth(root);
		System.out.println("width :" + width + " higth: " + higth);

		int r = 10;
		MTreePic jpanel = new MTreePic(root, (int) width * length + 50, (int) higth * length + 50, r);

		JFrame frame = new JFrame("Reingold-Tilford树生成: multiple tree");
		frame.setContentPane(jpanel);
		frame.setBounds(200, 200, jpanel.getWidth(), jpanel.getHeight());
		frame.setVisible(true);
		
	}
}
